package com.lxw.nonghe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxw.nonghe.entity.AdministrativeRegion;
import com.lxw.nonghe.mapper.AdministrativeRegionMapper;
import com.lxw.nonghe.service.AdministrativeRegionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 行政区域表 服务实现类
 * </p>
 *
 * @author lxw
 * @since 2025-05-09
 */
@Service
public class AdministrativeRegionServiceImpl extends ServiceImpl<AdministrativeRegionMapper, AdministrativeRegion> implements AdministrativeRegionService {

    @Override
    public Page<AdministrativeRegion> getRegionPage(int current, int size, String regionName) {
        Page<AdministrativeRegion> page = new Page<>(current, size);
        return (Page<AdministrativeRegion>) this.baseMapper.selectAdministrativeRegionPage(page, regionName);
    }

    @Override
    public AdministrativeRegion getRegionByName(String regionName) {
        return this.lambdaQuery().eq(AdministrativeRegion::getRegionName, regionName).one();
    }
    @Override
    public AdministrativeRegion getRegionByCode(String regionCode) {
        return this.lambdaQuery().eq(AdministrativeRegion::getRegionCode, regionCode).one();
    }
    @Override
    public Page<AdministrativeRegion> queryRegion(AdministrativeRegion queryRegion, int current, int size) {
        // 构建查询条件
        LambdaQueryWrapper<AdministrativeRegion> wrapper = new LambdaQueryWrapper<>();

        // 精确查询条件
        wrapper.eq(queryRegion.getRegionId() != null,
                        AdministrativeRegion::getRegionId, queryRegion.getRegionId())
                .eq(queryRegion.getLevel() != null,
                        AdministrativeRegion::getLevel, queryRegion.getLevel())
                .eq(queryRegion.getStatus() != null,
                        AdministrativeRegion::getStatus, queryRegion.getStatus())
                .eq(StringUtils.isNotBlank(queryRegion.getRegionCode()),
                        AdministrativeRegion::getRegionCode, queryRegion.getRegionCode())
                .eq(StringUtils.isNotBlank(queryRegion.getParentCode()),
                        AdministrativeRegion::getParentCode, queryRegion.getParentCode());

        // 模糊查询条件（String类型字段）
        wrapper.like(StringUtils.isNotBlank(queryRegion.getRegionName()),
                AdministrativeRegion::getRegionName, queryRegion.getRegionName());

        // 添加排序（按创建时间降序）
        wrapper.orderByDesc(AdministrativeRegion::getCreateTime);

        // 执行分页查询
        Page<AdministrativeRegion> page = new Page<>(current, size);
        return this.page(page, wrapper);
    }
}
